package com.lry.basic.thread;

import com.alibaba.ttl.TransmittableThreadLocal;
import com.alibaba.ttl.TtlCallable;
import com.alibaba.ttl.TtlRunnable;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

public class TTLTest2 {
    // 声明一个线程池
    private static final ExecutorService pool = Executors.newFixedThreadPool(2);
    // 声明一个TransmittableThreadLocal全局变量
    private static final ThreadLocal<String> tl = new TransmittableThreadLocal<>();

    public static void main(String[] args) {
        // 设置一个值
        tl.set("张三");

        System.out.println(Thread.currentThread().getName() + "--->" + tl.get());
        // 声明一个Runnable对象
        Runnable r1 = () -> {
            while(true){
                System.out.println(Thread.currentThread().getName() + "--->" + tl.get());
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        };
        // 使用TtlRunnable包装一下Runnable对象
        TtlRunnable ttlRunnable1 = TtlRunnable.get(r1);
        // 向线程池提交
        pool.submit(ttlRunnable1);
        // 声明一个Callable对象
        Callable<String> c1 = () -> {
            System.out.println(Thread.currentThread().getName() + "--->" + tl.get());
            return "success";
        };
        // 使用TtlCallable包装一下Callable对象
        TtlCallable<String> ttlCallable1 = TtlCallable.get(c1);
        // 向线程池提交
        pool.submit(ttlCallable1);

        tl.set("李四"); // 更新tl中的值
        try {
            TimeUnit.SECONDS.sleep(1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        System.out.println(Thread.currentThread().getName() + "--->" + tl.get());

        // 声明一个Runnable对象
        Runnable r2 = () -> {
            System.out.println(Thread.currentThread().getName() + "--->" + tl.get());
        };
        // 使用TtlRunnable包装一下Runnable对象
        TtlRunnable ttlRunnable2 = TtlRunnable.get(r2);
        // 向线程池提交
        pool.submit(ttlRunnable2);
        // 声明一个Callable对象
        Callable<String> c2 = () -> {
            System.out.println(Thread.currentThread().getName() + "--->" + tl.get());
            return "success";
        };
        // 使用TtlCallable包装一下Callable对象
        TtlCallable<String> ttlCallable2 = TtlCallable.get(c2);
        // 向线程池提交
        pool.submit(ttlCallable2);

        // 关闭线程池
        pool.shutdown();
    }
}